﻿define(['jquery', 'toastr'], function ($, Toastr) {
    'use strict';
    
    var AiHelper = {
        options: {
            generateUrl: 'ai/ai/generateImage',
            batchGenerateUrl: 'ai/ai/batchGenerate',
            getSizesUrl: 'ai/ai/getSupportedSizes',
            getStylesUrl: 'ai/ai/getSupportedStyles',
            getProviderUrl: 'ai/ai/getProviderInfo',
            defaultSize: '1024x1024',
            defaultStyle: 'default'
        },
        
        supportedSizes: [],
        supportedStyles: [],
        currentProvider: 'doubao',
        
        init: function(options) {
            this.options = $.extend(this.options, options || {});
            this.loadSupportedOptions();
            this.bindEvents();
            return this;
        },
        
        loadSupportedOptions: function() {
            var self = this;
            
            $.ajax({
                url: self.options.getProviderUrl,
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 1) {
                        self.currentProvider = response.data.provider;
                    }
                }
            });
            
            $.ajax({
                url: self.options.getSizesUrl,
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 1) {
                        self.supportedSizes = response.data.sizes || [];
                        self.options.defaultSize = response.data.default_size || '1024x1024';
                    }
                }
            });
            
            $.ajax({
                url: self.options.getStylesUrl,
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 1) {
                        self.supportedStyles = response.data.styles || [];
                    }
                }
            });
        },
        
        bindEvents: function() {
            var self = this;
            
            $(document).on('click', '[data-ai-generate]', function() {
                var $btn = $(this);
                var options = {
                    inputId: $btn.data('input-id'),
                    prompt: $btn.data('say'),
                    size: $btn.data('size') || self.options.defaultSize,
                    style: $btn.data('style') || self.options.defaultStyle,
                    previewId: $btn.data('preview-id')
                };
                
                self.generateImage($btn, options);
            });
            
            $(document).on('click', '[data-ai-batch-generate]', function() {
                var $btn = $(this);
                var prompts = $btn.data('prompts') || [];
                var options = {
                    size: $btn.data('size') || self.options.defaultSize,
                    style: $btn.data('style') || self.options.defaultStyle
                };
                
                self.batchGenerate($btn, prompts, options);
            });
        },
        
        generateImage: function($btn, options) {
            var self = this;
            
            if (!options.prompt || !options.prompt.trim()) {
                self.showError('Please enter a prompt');
                return;
            }
            
            var originalText = $btn.html();
            var originalDisabled = $btn.prop('disabled');
            
            $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Generating...');
            
            // 解析尺寸参数
            var width = '', height = '';
            if (options.size) {
                if (options.size.indexOf('*') !== -1) {
                    var sizeParts = options.size.split('*');
                    width = sizeParts[0];
                    height = sizeParts[1];
                } else if (options.size.indexOf('x') !== -1) {
                    var sizeParts = options.size.split('x');
                    width = sizeParts[0];
                    height = sizeParts[1];
                }
            }

            $.ajax({
                url: self.options.generateUrl,
                type: 'POST',
                data: {
                    prompt: options.prompt,
                    size: options.size,
                    width: width,
                    height: height,
                    type: options.type || 'image',
                    style: options.style
                },
                dataType: 'json',
                timeout: 60000,
                success: function(response) {
                    if (response.code === 1) {
                        var imageUrl = response.data.url;
                        var localPath = response.data.local_path;
                        
                        if (options.inputId) {
                            $('#' + options.inputId).val(localPath).trigger('change');
                        }
                        
                        if (options.previewId) {
                            $('#' + options.previewId).attr('src', imageUrl).show();
                        }
                        
                        self.showSuccess('Image generated successfully!');
                    } else {
                        self.showError(response.msg || 'Image generation failed');
                    }
                },
                error: function(xhr, status, error) {
                    if (status === 'timeout') {
                        self.showError('Request timeout, please try again later');
                    } else {
                        self.showError('Network error, please check your connection');
                    }
                },
                complete: function() {
                    $btn.prop('disabled', originalDisabled).html(originalText);
                }
            });
        },
        
        batchGenerate: function($btn, prompts, options) {
            var self = this;
            
            if (!prompts || prompts.length === 0) {
                self.showError('Please provide prompt list');
                return;
            }
            
            var originalText = $btn.html();
            var originalDisabled = $btn.prop('disabled');
            
            $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Batch generating...');
            
            $.ajax({
                url: self.options.batchGenerateUrl,
                type: 'POST',
                data: {
                    prompts: prompts,
                    size: options.size,
                    style: options.style
                },
                dataType: 'json',
                timeout: 60000 * prompts.length,
                success: function(response) {
                    if (response.code === 1) {
                        var data = response.data;
                        var successCount = data.success_count || 0;
                        var totalCount = data.total_count || prompts.length;
                        
                        if (successCount === totalCount) {
                            self.showSuccess('Batch generation completed! Successfully generated ' + successCount + ' images');
                        } else {
                            self.showError('Batch generation partially successful, ' + successCount + '/' + totalCount + ' images generated');
                        }
                        
                        $(document).trigger('ai:batchGenerateComplete', [data]);
                    } else {
                        self.showError(response.msg || 'Batch generation failed');
                    }
                },
                error: function(xhr, status, error) {
                    if (status === 'timeout') {
                        self.showError('Batch generation timeout, please try again later');
                    } else {
                        self.showError('Network error, please check your connection');
                    }
                },
                complete: function() {
                    $btn.prop('disabled', originalDisabled).html(originalText);
                }
            });
        },
        
        showSuccess: function(message) {
            Toastr.success(message);
        },
        
        showError: function(message) {
            Toastr.error(message);
        },
        
        getSupportedSizes: function(callback) {
            $.ajax({
                url: this.options.getSizesUrl,
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 1 && callback) {
                        callback(response.data);
                    }
                }
            });
        },
        
        getSupportedStyles: function(callback) {
            $.ajax({
                url: this.options.getStylesUrl,
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 1 && callback) {
                        callback(response.data);
                    }
                }
            });
        },
        
        testConnection: function(callback) {
            $.ajax({
                url: this.options.getProviderUrl,
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (callback) {
                        callback(response.code === 1, response.msg);
                    }
                },
                error: function() {
                    if (callback) {
                        callback(false, 'Connection test failed');
                    }
                }
            });
        }
    };
    
    return AiHelper;
});
